package cn.dnui_xqh414.dnuifood_16110100414;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import cn.dnui_xqh414.dnuifood_16110100414.bean.ResultBean;
import cn.dnui_xqh414.dnuifood_16110100414.bean.UserInfo;
import cn.dnui_xqh414.dnuifood_16110100414.bean.Userbean;
import cn.dnui_xqh414.dnuifood_16110100414.listener.OnRetrofitListener;
import cn.dnui_xqh414.dnuifood_16110100414.model.UserModel;

import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.mcxtzhang.lib.AnimShopButton;
import com.mcxtzhang.lib.IOnAddDelListener;
import com.squareup.picasso.Picasso;

import java.util.Calendar;
import java.util.Locale;
import java.util.Objects;

import static android.widget.Toast.LENGTH_SHORT;

public class PayActivity extends BaseActivity
        implements OnRetrofitListener {

    private ImageView img_foodImg;
    private TextView tv_foodName,tv_foodPrice,tv_totalPrice,tv_moblieNum;
    private AnimShopButton buttonNum;
    private MaterialButton buttonBuy;
    private Toolbar toolbar;
    private EditText rt_address;

    private TextInputLayout textInputLayout_from,textInputLayout_to;
    private TextInputEditText textInputEditText_from,textInputEditText_to;

    private double total;
    private int num = 1;

    private int hourFrom,minteFrom;
    private int hourTo,minteTo;

    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("SetTextI18n")
    @Override
    void initViews() {
        setContentView(R.layout.activity_pay);

        toolbar = findViewById(R.id.toolbar_order);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(String.valueOf(getIntent().getStringExtra("foodName")));

        rt_address = findViewById(R.id.rt_order_address);
        img_foodImg = findViewById(R.id.img_order_foodPic);
        tv_foodName = findViewById(R.id.tv_order_foodName);
        tv_foodPrice = findViewById(R.id.tv_order_price);
        tv_totalPrice = findViewById(R.id.tv_order_totalPrice);
        tv_moblieNum = findViewById(R.id.tv_order_mobileNum);
        buttonNum = findViewById(R.id.sbt_chooseNum);
        buttonBuy = findViewById(R.id.bt_buybuybuy);
        textInputLayout_from = findViewById(R.id.tl_timeFrom);
        textInputLayout_to = findViewById(R.id.tl_timeTo);
        textInputEditText_from = findViewById(R.id.tie_timeFrom);
        textInputEditText_to = findViewById(R.id.tie_timeTo);

        tv_foodPrice.setText("￥"+String.valueOf(getIntent().getDoubleExtra("foodPrice",0)));
        tv_totalPrice.setText("￥"+String.valueOf(getIntent().getDoubleExtra("foodPrice",0)));
//        tv_moblieNum.setText(String.valueOf(userInfo.getMobilenum()));
//        Toast.makeText(this, userInfo.getMobilenum()+"??", Toast.LENGTH_SHORT).show();
        tv_foodName.setText(String.valueOf(getIntent().getStringExtra("foodName")));

        String url =
                "http://172.24.10.175:8080/foodService/"+getIntent().getStringExtra("foodPic");
        Picasso.get()
                .load(url)
                .placeholder(R.drawable.ic_loading)
                .error(R.drawable.ic_load_fail_sfont)
                .fit()
                .centerCrop()
                .into(img_foodImg);
    }

    @Override
    void initEvents() {

        buttonNum.setOnAddDelListener(new IOnAddDelListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onAddSuccess(int i) {
                total = getIntent().getDoubleExtra("foodPrice",0)*buttonNum.getCount();
                num = buttonNum.getCount();
                tv_totalPrice.setText("￥"+String.valueOf(total));
//                Toast.makeText(PayActivity.this, String.valueOf(buttonNum.getCount()), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAddFailed(int i, FailType failType) {
//                Toast.makeText(PayActivity.this, "onAddFailed", Toast.LENGTH_SHORT).show();
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onDelSuccess(int i) {
                total = getIntent().getDoubleExtra("foodPrice",0)*buttonNum.getCount();
                num = buttonNum.getCount();
                tv_totalPrice.setText("￥"+String.valueOf(total));
//                Toast.makeText(PayActivity.this, "onDelSuccess", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDelFaild(int i, FailType failType) {
//                Toast.makeText(PayActivity.this, "onDelFaild", Toast.LENGTH_SHORT).show();
            }
        });

        textInputEditText_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog(new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        hourFrom = hourOfDay;
                        minteFrom = minute;
                        textInputEditText_from.
                                setText(String.format(Locale.ENGLISH,"%d:%d",hourOfDay,minute));
                    }
                });
            }
        });

        textInputEditText_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog(new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        hourTo = hourOfDay;
                        minteTo = minute;
                        textInputEditText_to.
                                setText(String.format(Locale.ENGLISH,"%d:%d",hourOfDay,minute));
                    }
                });
            }
        });

        textInputEditText_from.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    showTimePickerDialog(new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            hourFrom = hourOfDay;
                            minteFrom = minute;
                            textInputEditText_from.
                                    setText(String.format(Locale.ENGLISH,"%d:%d",hourOfDay,minute));
                        }
                    });
            }
        });

        textInputEditText_to.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    showTimePickerDialog(new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            hourTo = hourOfDay;
                            minteTo = minute;
                            textInputEditText_to.
                                    setText(String.format(Locale.ENGLISH,"%d:%d",hourOfDay,minute));
                        }
                    });
            }
        });

        buttonBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textInputLayout_from.setErrorEnabled(false);
                textInputLayout_to.setErrorEnabled(false);
//                Toast.makeText(PayActivity.this, String.valueOf(hourTo-hourFrom),
//                        LENGTH_SHORT).show();
                boolean i = true;
                if ((hourTo-hourFrom)<0){
//                    Toast.makeText(PayActivity.this, String.valueOf(minteTo-minteFrom), Toast.LENGTH_SHORT).show();
                    showError(textInputLayout_from,"Please select correct time");
                    i = false;
                }else{
                    if (hourTo-hourFrom==0){
                        if (minteTo-minteFrom<=0){
                            showError(textInputLayout_to,"Please select correct time");
                            i = false;
                        }
                    }else{
                        if (minteTo-minteFrom<0){
                            showError(textInputLayout_to,"Please select correct time");
                            i = false;
                        }
                    }
                }

//                Toast.makeText(PayActivity.this, rt_address.getText()+"??", Toast.LENGTH_SHORT).show();
                if (rt_address.getText().toString().equals("")){
                    Toast.makeText(PayActivity.this, "请填写地址", LENGTH_SHORT).show();
                    i = false;
                }
                if (i){
                    SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                    int userid = sharedPreferences.getInt("userid",-1);
                    int foodId = getIntent().getIntExtra("foodId",-1);
                    UserModel model = new UserModel();
                    model.JustBuyIt(userid, foodId, num,
                            (int) getIntent().getDoubleExtra("foodPrice", 0) * num,
                            Objects.requireNonNull(textInputEditText_from.
                                    getText()).toString()+"-"+Objects.requireNonNull(textInputEditText_to.
                                    getText()).toString(),
                            rt_address.getText().toString(), new OnRetrofitListener<ResultBean>() {
                                @Override
                                public void onSuccess(ResultBean object, int flag) {
                                    if (object.getSuccess().equals("1")){
                                        Toast.makeText(PayActivity.this, "购买成功", LENGTH_SHORT).show();
                                    }else {
                                        Toast.makeText(PayActivity.this, "未知错误", LENGTH_SHORT).show();
                                    }
                                }

                                @Override
                                public void onFailure(String msg) {

                                }
                            });
                }
            }
        });
    }

    @Override
    void initData() {
        //    phoneNum
        //    foodPrice
        //    foodName
        //    foodPic
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
        int userid = sharedPreferences.getInt("userid",-1);
        UserModel userModel = new UserModel();
        userModel.getUser(userid, new OnRetrofitListener<UserInfo>() {
            @Override
            public void onSuccess(UserInfo object, int flag) {
                userInfo = object;
                tv_moblieNum.setText(String.valueOf(userInfo.getMobilenum()));
                rt_address.setText(String.valueOf(userInfo.getAddress()));
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
                default:
                    return false;
        }
        return true;
    }

    @Override
    public void onSuccess(Object object, int flag) {

    }

    @Override
    public void onFailure(String msg) {
    }

    private void showTimePickerDialog(TimePickerDialog.OnTimeSetListener listener){
        Calendar calendar = Calendar.getInstance();
//        TimePickerDialog(this,listener,calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show;
        new TimePickerDialog(this,
                listener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true).show();

    }

    private void showError(TextInputLayout layout, String error){
        layout.setError(error);
        Objects.requireNonNull(layout.getEditText()).setFocusable(true);
        layout.getEditText().setFocusableInTouchMode(true);
        layout.getEditText().requestFocus();
    }
}
